package com.woniuxy.ams.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

/**
 * @author fyxw
 */
public class JwtUtils {
    private static final String SECURITY = "WONIUXY";
    private JwtUtils(){}

    /**
     * 签名生成jwt
     * @param username 用户名
     * @return token
     */
    public static String sign(String username){
        //对唯一秘钥进行加密使用
        Algorithm algorithm = Algorithm.HMAC256(SECURITY);
        return JWT.create()
                .withClaim("username",username)
                .withClaim("creatTime",System.currentTimeMillis())
                //签名 如果签名不对，则无法解析jwt
                .sign(algorithm);
    }


    /**
     * @param token 传入token
     * @param claimName 传入需要获取的字段
     * @return 返回字段的值
     */
    public static String getClaim(String token, String claimName){
        DecodedJWT jwt = JWT.decode(token);
        Claim claim = jwt.getClaim(claimName);
        return claim.asString();
    }
}